package com.zenithmind.classroom.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zenithmind.classroom.pojo.domain.CourseLesson;
import com.zenithmind.classroom.pojo.vo.LessonDetailVO;
import com.zenithmind.classroom.pojo.vo.LessonVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 课程课时Mapper接口
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Mapper
public interface CourseLessonMapper extends BaseMapper<CourseLesson> {

    /**
     * 获取章节课时列表（包含用户进度）
     * 
     * @param chapterId 章节ID
     * @param userId 用户ID
     * @param includeUnpublished 是否包含未发布
     * @return 课时列表
     */
    List<LessonVO> selectChapterLessonsWithProgress(@Param("chapterId") String chapterId, 
                                                   @Param("userId") String userId, 
                                                   @Param("includeUnpublished") Boolean includeUnpublished);

    /**
     * 获取课程课时列表（包含用户进度）
     * 
     * @param courseId 课程ID
     * @param userId 用户ID
     * @param includeUnpublished 是否包含未发布
     * @return 课时列表
     */
    List<LessonVO> selectCourseLessonsWithProgress(@Param("courseId") String courseId, 
                                                  @Param("userId") String userId, 
                                                  @Param("includeUnpublished") Boolean includeUnpublished);

    /**
     * 获取课时详情（包含用户进度）
     * 
     * @param lessonId 课时ID
     * @param userId 用户ID
     * @return 课时详情
     */
    LessonDetailVO selectLessonDetailWithProgress(@Param("lessonId") String lessonId, @Param("userId") String userId);

    /**
     * 更新课时统计
     * 
     * @param lessonId 课时ID
     * @return 影响行数
     */
    @Update("UPDATE classroom_course_lesson SET " +
            "view_count = (SELECT COUNT(*) FROM lesson_view_record WHERE lesson_id = #{lessonId}), " +
            "completed_count = (SELECT COUNT(*) FROM learning_progress WHERE lesson_id = #{lessonId} AND status = 2), " +
            "update_time = NOW() " +
            "WHERE id = #{lessonId}")
    int updateLessonStatistics(@Param("lessonId") String lessonId);

    /**
     * 获取课时学习进度
     * 
     * @param lessonId 课时ID
     * @param userId 用户ID
     * @return 进度百分比
     */
    @Select("SELECT COALESCE(progress_percentage, 0) " +
            "FROM learning_progress " +
            "WHERE lesson_id = #{lessonId} AND user_id = #{userId} AND deleted = 0 LIMIT 1")
    Integer getLessonProgress(@Param("lessonId") String lessonId, @Param("userId") String userId);

    /**
     * 批量更新课时排序
     * 
     * @param lessonIds 课时ID列表（按新顺序）
     * @param chapterId 章节ID
     * @return 影响行数
     */
    int batchUpdateLessonOrder(@Param("lessonIds") List<String> lessonIds, @Param("chapterId") String chapterId);

    /**
     * 获取课时最大排序值
     * 
     * @param chapterId 章节ID
     * @return 最大排序值
     */
    @Select("SELECT COALESCE(MAX(sort_order), 0) FROM classroom_course_lesson WHERE chapter_id = #{chapterId} AND deleted = 0")
    Integer getMaxSortOrder(@Param("chapterId") String chapterId);

    /**
     * 移动课时到其他章节
     * 
     * @param lessonId 课时ID
     * @param targetChapterId 目标章节ID
     * @param newSortOrder 新排序值
     * @return 影响行数
     */
    @Update("UPDATE classroom_course_lesson SET " +
            "chapter_id = #{targetChapterId}, " +
            "sort_order = #{newSortOrder}, " +
            "update_time = NOW() " +
            "WHERE id = #{lessonId}")
    int moveLessonToChapter(@Param("lessonId") String lessonId, 
                           @Param("targetChapterId") String targetChapterId, 
                           @Param("newSortOrder") Integer newSortOrder);

    /**
     * 获取下一个课时
     * 
     * @param currentLessonId 当前课时ID
     * @param userId 用户ID
     * @return 下一个课时
     */
    LessonVO selectNextLesson(@Param("currentLessonId") String currentLessonId, @Param("userId") String userId);

    /**
     * 获取上一个课时
     * 
     * @param currentLessonId 当前课时ID
     * @param userId 用户ID
     * @return 上一个课时
     */
    LessonVO selectPreviousLesson(@Param("currentLessonId") String currentLessonId, @Param("userId") String userId);

    /**
     * 复制课时
     * 
     * @param sourceLessonId 源课时ID
     * @param targetChapterId 目标章节ID
     * @param newTitle 新标题
     * @param newSortOrder 新排序值
     * @return 新课时ID
     */
    String copyLesson(@Param("sourceLessonId") String sourceLessonId, 
                     @Param("targetChapterId") String targetChapterId, 
                     @Param("newTitle") String newTitle, 
                     @Param("newSortOrder") Integer newSortOrder);

    /**
     * 获取课时播放地址
     * 
     * @param lessonId 课时ID
     * @param userId 用户ID
     * @return 播放地址
     */
    @Select("SELECT video_url FROM classroom_course_lesson " +
            "WHERE id = #{lessonId} AND " +
            "(is_free = 1 OR EXISTS(SELECT 1 FROM course_enrollment WHERE user_id = #{userId} AND course_id = " +
            "(SELECT course_id FROM classroom_course_lesson WHERE id = #{lessonId})))")
    String getLessonPlayUrl(@Param("lessonId") String lessonId, @Param("userId") String userId);

    /**
     * 记录课时观看
     * 
     * @param lessonId 课时ID
     * @param userId 用户ID
     * @param watchTime 观看时长
     * @param position 观看位置
     * @return 影响行数
     */
    int recordLessonWatch(@Param("lessonId") String lessonId, 
                         @Param("userId") String userId, 
                         @Param("watchTime") Integer watchTime, 
                         @Param("position") Integer position);

    /**
     * 标记课时完成
     * 
     * @param lessonId 课时ID
     * @param userId 用户ID
     * @return 影响行数
     */
    int completeLessonStudy(@Param("lessonId") String lessonId, @Param("userId") String userId);

    /**
     * 检查课时是否属于指定章节
     * 
     * @param lessonId 课时ID
     * @param chapterId 章节ID
     * @return 是否属于
     */
    @Select("SELECT COUNT(*) > 0 FROM classroom_course_lesson WHERE id = #{lessonId} AND chapter_id = #{chapterId} AND deleted = 0")
    Boolean checkLessonBelongsToChapter(@Param("lessonId") String lessonId, @Param("chapterId") String chapterId);

    /**
     * 检查用户是否有课时访问权限
     * 
     * @param lessonId 课时ID
     * @param userId 用户ID
     * @return 是否有权限
     */
    @Select("SELECT (cl.is_free = 1 OR EXISTS(SELECT 1 FROM course_enrollment ce WHERE ce.user_id = #{userId} AND ce.course_id = cl.course_id AND ce.deleted = 0)) " +
            "FROM classroom_course_lesson cl WHERE cl.id = #{lessonId} AND cl.deleted = 0")
    Boolean checkLessonAccess(@Param("lessonId") String lessonId, @Param("userId") String userId);

    /**
     * 上传课时资源
     * 
     * @param lessonId 课时ID
     * @param resourceType 资源类型
     * @param resourceUrl 资源URL
     * @param resourceSize 资源大小
     * @return 影响行数
     */
    @Update("UPDATE classroom_course_lesson SET " +
            "video_url = CASE WHEN #{resourceType} = 'video' THEN #{resourceUrl} ELSE video_url END, " +
            "audio_url = CASE WHEN #{resourceType} = 'audio' THEN #{resourceUrl} ELSE audio_url END, " +
            "document_url = CASE WHEN #{resourceType} = 'document' THEN #{resourceUrl} ELSE document_url END, " +
            "resource_size = #{resourceSize}, " +
            "update_time = NOW() " +
            "WHERE id = #{lessonId}")
    int uploadLessonResource(@Param("lessonId") String lessonId, 
                            @Param("resourceType") String resourceType, 
                            @Param("resourceUrl") String resourceUrl, 
                            @Param("resourceSize") Long resourceSize);
}
